package driver.android;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.Permission;
import com.luck.picture.lib.permissions.RxPermissions;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import driver.android.adapter.GridImageAdapter;
import driver.android.http.CommonOkHttpClient;
import driver.android.view.CountDownView;
import driver.android.view.FullyGridLayoutManager;
import driver.android.view.SlideToggleView;
import driver.util.Constants;
import driver.util.IHttpCallBack;
import driver.util.Util;
import io.reactivex.functions.Consumer;
import okhttp3.Response;

public class FlashDriverTaskDetailActivity extends Activity implements IHttpCallBack, View.OnClickListener, LocationListener, SlideToggleView.SlideToggleListener, CountDownView.OnCountDownFinishListener {

    private String mLoginToken;
    private String mUuid;
    private String mTaskId;
    private Button mDeclineTask;
    private TextView mTaskOffer;
    private TextView mCollectAtTimeTv;
    private TextView mPickUpNumber;
    private TextView mPickUpSecureNumberSub;
    private TextView mPickUpSecureNumber;
    private EditText mCollectEditText;
    private Button mCollectNavigator;
    private SlideToggleView mSlideToggleView;
    private TextView mTaskCollectDistance;
    private EditText mDeliverEditText;
    private TextView mDeliveryNotes;
    private Button mDeliverNavigatorIcon;
    private RelativeLayout mTaskLitterSummerLayout;
    private RelativeLayout mTaskCutParentLayout;
    private TextView mTaskTotalFeeSummaryTv;
    private LinearLayout mTaskDetailSummaryParentLayout;
    private LinearLayout mTaskDetailFeeParentLayout;
    private TextView mTaskFeePriceTv;
    private RelativeLayout mTaskDetail212Layout;
    private EditText mTaskDetailNoteEditText;
    private RelativeLayout mTask202IdLayout;
    private RelativeLayout mTaskPickUpNumberLayout;
    private TextView mTask202IdTv;
    private TextView mTaskCollectNotes;
    private EditText mTask202DetailEditText;
    private ProgressDialog mProgressDialog;
    private FlashDriverTaskDetailHandler mHandler;
    private LocationManager mLocationManager;
    private String mLatitude; //current Latitude
    private String mLongitude; //current Longitude
    private CountDownView mCountDownView;
    private TextView mTaskReName;
    private TextView mTaskRePhone;
    private TextView mTaskFeeSumSub;
    private TextView mTaskFeeSumAfter;
    private SharedPreferences mFlashSharedPreferences;
    private String mFlashSharePreferenceName = "Flash";
    private String mPickUpLocation = "";
    private int maxSelectNum = 2;
    private String mUpdateLocation = "false";
    private List<LocalMedia> selectList = new ArrayList<>();
    private GridImageAdapter adapter;
    private RecyclerView mRecyclerView;
    private PopupWindow pop;
    private RelativeLayout mAddPicsLayout;
    private RelativeLayout mAddNoteLayout;
    private EditText mEditNote;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Util.debugApp('d', "task detail activity onCreate");
        this.setContentView(R.layout.f_task_detail_activity);
        initView();
        boolean connect = Util.isNetworkAvailable(this);
        if (!connect) {
            showToast("Please check your network state");
            mSlideToggleView.setClickable(false);
            return;
        }
//        if (mTaskId != null && !mTaskId.equals("null") && mTaskId.length() > 0) {
//            this.showProgressDialog("Please wait...");
//            this.sendTaskItemDetail(mTaskId);
//        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Util.debugApp('d', "task detail activity onResume " + mTaskId);
        this.registerLocationListen();
        if (mTaskId != null && !mTaskId.equals("null") && mTaskId.length() > 0) {
            this.showProgressDialog("Please wait...");
            if (mHandler != null) {
                Message taskDetailMessage = mHandler.obtainMessage();
                if (taskDetailMessage != null) {
                    taskDetailMessage.what = Constants.GET_TASK_DETAIL;
                    mHandler.sendMessageDelayed(taskDetailMessage, 400);
//            this.sendTaskItemDetail(mTaskId);
                }
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Util.debugApp('d', "task detail activity on pause");
        mLocationManager.removeUpdates(this);
        if (mCountDownView != null && mCountDownView.isShown()) {
            Util.debugApp('d', "task detail close curt down");
            mCountDownView.stopCountDown();
        }
    }

    private void initView() {
        mFlashSharedPreferences = getSharedPreferences(mFlashSharePreferenceName, Context.MODE_PRIVATE);
        mDeclineTask = (Button) this.findViewById(R.id.decline_task);
        mTaskOffer = (TextView) this.findViewById(R.id.task_new_offer);
        mTaskCollectNotes = (TextView) this.findViewById(R.id.task_collect_notes);
        mCollectAtTimeTv = (TextView) this.findViewById(R.id.task_collect_time_text);
        mPickUpSecureNumberSub = (TextView) this.findViewById(R.id.task_pickup_secure_code_sub);
        mPickUpNumber = (TextView) this.findViewById(R.id.task_pickup_order_number);
        mPickUpSecureNumber = (TextView) this.findViewById(R.id.task_pickup_secure_code);
        mCollectEditText = (EditText) this.findViewById(R.id.task_collect_edit_text);
        mCollectNavigator = (Button) this.findViewById(R.id.task_collect_navigation);
        mTaskCutParentLayout = (RelativeLayout) this.findViewById(R.id.task_collect_cut_deliver_parent);
        mTaskCollectDistance = (TextView) this.findViewById(R.id.task_collect_cut_deliver_distance);
        mDeliverEditText = (EditText) this.findViewById(R.id.task_deliver_edit_text);
        mDeliverNavigatorIcon = (Button) this.findViewById(R.id.task_deliver_navigation);
        mTaskLitterSummerLayout = (RelativeLayout) this.findViewById(R.id.task_litter_summary_layout);
        mDeliveryNotes = (TextView) this.findViewById(R.id.task_delivery_notes);
        mTaskReName = (TextView) this.findViewById(R.id.task_r_name);
        mTaskRePhone = (TextView) this.findViewById(R.id.task_r_Phone);
        mTaskTotalFeeSummaryTv = (TextView) this.findViewById(R.id.task_total_fee_summary);
        mTaskFeeSumSub = (TextView) this.findViewById(R.id.task_order_numbers);
        mTaskFeeSumAfter = (TextView) this.findViewById(R.id.task_total_fee);
        mTaskFeePriceTv = (TextView) this.findViewById(R.id.task_fee_price);
        mTaskDetail212Layout = (RelativeLayout) this.findViewById(R.id.task_detail_212_layout_note);
        mTaskDetailNoteEditText = (EditText) this.findViewById(R.id.task_detail_note);
        mTask202IdLayout = (RelativeLayout) this.findViewById(R.id.task_202_id_layout);
        mTask202IdTv = (TextView) this.findViewById(R.id.task_202_id);
        mCountDownView = (CountDownView) this.findViewById(R.id.task_201_count_down_view);
        mCountDownView.setAddCountDownListener(this);
        mTaskDetailSummaryParentLayout = (LinearLayout) this.findViewById(R.id.task_detail_summary_parent_layout);
        mTaskDetailFeeParentLayout = (LinearLayout) this.findViewById(R.id.task_detail_fee_parent_layout);
        mTask202DetailEditText = (EditText) this.findViewById(R.id.task_202_detail_edit_text);
        mSlideToggleView = (SlideToggleView) this.findViewById(R.id.task_detail_slide_toggle_view);
        mSlideToggleView.setSlideToggleListener(this);
        mTaskPickUpNumberLayout = (RelativeLayout) this.findViewById(R.id.task_pickup_order_number_layout);
        mTask202IdTv.setOnClickListener(this);
        mProgressDialog = new ProgressDialog(this);
        mHandler = new FlashDriverTaskDetailHandler(this);
        mCollectNavigator.setOnClickListener(this);
        mDeliverNavigatorIcon.setOnClickListener(this);
        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        mRecyclerView = findViewById(R.id.recycler);
        mAddPicsLayout = (RelativeLayout) this.findViewById(R.id.task_add_pics_layout);
        mAddPicsLayout.setVisibility(View.GONE);
        mAddNoteLayout = (RelativeLayout) this.findViewById(R.id.task_note_layout);
        mAddNoteLayout.setVisibility(View.GONE);
        mEditNote = (EditText) this.findViewById(R.id.add_note_edit_text);
        Bundle bundle = this.getIntent().getExtras();
        if (bundle != null) {
            mLoginToken = bundle.getString("token");
            mUuid = bundle.getString("uuid");
            mTaskId = bundle.getString("taskId");
            String maxUploadPics = bundle.getString("maxUploadPics");
            if (TextUtils.isEmpty(maxUploadPics)) {
                maxSelectNum = 2;
            } else {
                maxSelectNum = Integer.parseInt(maxUploadPics);
            }
            mUpdateLocation = bundle.getString("mUpdateLocation");
            Util.debugApp('d', "task detail update location flag " + mUpdateLocation);
        }
        initWidget();
    }

    private void initWidget() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        adapter = new GridImageAdapter(this, onAddPicClickListener, maxSelectNum);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        mRecyclerView.setAdapter(adapter);
    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {

        @SuppressLint("CheckResult")
        @Override
        public void onAddPicClick() {
            RxPermissions rxPermission = new RxPermissions(FlashDriverTaskDetailActivity.this);
            rxPermission.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(new Consumer<Permission>() {
                        @Override
                        public void accept(Permission permission) {
                            if (permission.granted) {
                                showPop();
                            } else {
                                Toast.makeText(FlashDriverTaskDetailActivity.this, "Allow access photos to upload photos for delivery proof", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        }
    };

    private void showPop() {
        View bottomView = View.inflate(FlashDriverTaskDetailActivity.this, R.layout.layout_bottom_dialog, null);
        TextView mAlbum = bottomView.findViewById(R.id.tv_album);
        TextView mCamera = bottomView.findViewById(R.id.tv_camera);
        pop = new PopupWindow(bottomView, -1, -2);
        pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        pop.setOutsideTouchable(true);
        pop.setFocusable(true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        pop.setAnimationStyle(R.style.main_menu_photo_anim);
        pop.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);

        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.tv_album:
                        // click album
                        PictureSelector.create(FlashDriverTaskDetailActivity.this)
                                .openGallery(PictureMimeType.ofImage())
                                .maxSelectNum(maxSelectNum)
                                .minSelectNum(1)
                                .imageSpanCount(4)
                                .compress(true)
                                .minimumCompressSize(100)
                                .isCamera(false)
                                .selectionMode(PictureConfig.MULTIPLE)
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                        break;
                    case R.id.tv_camera:
                        // click camera
                        PictureSelector.create(FlashDriverTaskDetailActivity.this)
                                .openCamera(PictureMimeType.ofImage())
                                .compress(true)
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                        break;
                }
                closePopupWindow();
            }
        };

        mAlbum.setOnClickListener(clickListener);
        mCamera.setOnClickListener(clickListener);
    }

    public void closePopupWindow() {
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
            pop = null;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> images;
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) { // call back when selected pic
                images = PictureSelector.obtainMultipleResult(data);
                Util.debugApp('d', "get pic info" + images.get(0).getPath());
                selectList.addAll(images);
                adapter.setList(selectList);
                adapter.notifyDataSetChanged();
            }
        }
    }

    private void showToast(String title) {
        Toast.makeText(this, title, Toast.LENGTH_LONG).show();
    }

    private void registerLocationListen() {
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "Please Allow Location Permission", Toast.LENGTH_LONG).show();
            return;
        }
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 0, this);
        mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L, 0, this);
    }

    private void updateWithNewLocation(Location location) {
        mLatitude = String.valueOf(location.getLatitude());
        mLongitude = String.valueOf(location.getLongitude());
        Util.debugApp('d', "current mLatitude " + mLatitude + " current  mLongitude " + mLongitude);
        if (Util.DEBUG) {
            showToast("current mLatitude " + mLatitude + " current  mLongitude " + mLongitude);
        }
        mLocationManager.removeUpdates(this);
//        this.showGoogleMapAc(mPickUpLocation);
    }

    private void showGoogleMapAc(String location) {
        if (!isHasGPSModule() || !checkGPSIsOpen()) {
            Toast.makeText(this, "Please Open GPS", Toast.LENGTH_LONG).show();
        } else {
            Util.debugApp('d', "show Google Map Activity " + mLatitude + " " + mLongitude);
            try {
                if (!TextUtils.isEmpty(mLatitude) && !TextUtils.isEmpty(mLongitude)) {
                    String url = "https://www.google.com/maps/dir/?api=1&origin=" + mLatitude + "," + mLongitude + "&destination=" + location + "&travelmode=driving" + "&key=" + this.getString(R.string.google_map_key);
                    Util.debugApp('d', "show google map URL " + url);
                    Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(url));
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addCategory(Intent.CATEGORY_LAUNCHER);
                    intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
                    startActivity(intent);
                }
            } catch (Exception e) {
                Util.debugApp('d', "google map exception");
            }
        }
    }

    private void showLoginActivity() {
        SharedPreferences.Editor editor = mFlashSharedPreferences.edit();
        editor.putString("token", "");
        editor.putString("uuid", "");
        editor.commit();
        Intent intent = new Intent();
        intent.setClass(this, FlashDriverLoginActivity.class);
        this.startActivity(intent);
        this.finish();
    }

    //    parse task json
    private void parseDetailContent(Bundle bundle) {
        String detailContent = bundle.get("taskBody").toString();
        Util.debugApp('d', "parseDetailContent " + detailContent);
        HashMap<String, String> taskDetailAllMap = Util.parseResponse(detailContent);
        if (taskDetailAllMap != null) {
            String taskDetail = taskDetailAllMap.get("task_detail");
            if (taskDetail != null && taskDetail.length() > 0) {
                HashMap<String, String> taskDetailMap = Util.parseResponse(taskDetail);
                Util.debugApp('d', "task_status_id " + taskDetailMap.get("task_status_id").toString());
                String earnings = taskDetailAllMap.get("earnings_detail");
                if (earnings != null) {
                    HashMap<String, String> taskEarningsMap = Util.parseResponse(earnings);
                    updateWholeUi(taskDetailAllMap, taskDetailMap, taskEarningsMap);
                }
            } else {
                Util.debugApp('d', "no task_detail ");
                mTaskDetailSummaryParentLayout.setVisibility(View.GONE);
                mTaskDetailFeeParentLayout.setVisibility(View.GONE);
                Toast.makeText(this, "No thing to Show", Toast.LENGTH_LONG).show();
            }
        } else {
            Util.debugApp('d', "is not json info");
        }
    }

    private void updateWholeUi(HashMap all, HashMap detail, HashMap earning) {
        String taskStatusId = detail.get("task_status_id") == null ? "" : detail.get("task_status_id").toString();
        Util.debugApp('d', "updateWholeUi  taskStatusId " + taskStatusId);
        mDeclineTask.setVisibility(View.GONE);
        String taskStatus = detail.get("task_status") == null ? "" : detail.get("task_status").toString();
        controlViewShowState(taskStatus, mTaskOffer, null);
        String collectDateTime = detail.get("collect_datetime") == null ? "" : detail.get("collect_datetime").toString();
        String time = Util.parseDateToTime(collectDateTime);
        controlViewShowState(time, mCollectAtTimeTv, null);
        String pickUpLocationDisPlay = detail.get("pickup_location_display") == null ? "" : detail.get("pickup_location_display").toString();
        String collectEdit = (detail.get("s_name") == null ? "" : detail.get("s_name").toString()) + pickUpLocationDisPlay;
        controlViewShowState(collectEdit, mCollectEditText, null);
        String collectNotes = detail.get("collect_notes") == null ? "" : detail.get("collect_notes").toString();
        if (collectNotes.length() > 0 && !collectNotes.equals("null")) {
            mTaskCollectNotes.setVisibility(View.VISIBLE);
            mTaskCollectNotes.setText("[ " + collectNotes + " ]");
        } else {
            mTaskCollectNotes.setVisibility(View.GONE);
        }
        String pickUpLocation = all.get("pickup_location") == null ? "" : all.get("pickup_location").toString();
        mCollectNavigator.setTag(R.id.pickup_location, pickUpLocation);
        String distance = detail.get("distance") == null ? "" : detail.get("distance").toString();
        controlViewShowState(distance, mTaskCollectDistance, mTaskCutParentLayout);
        String deliverLocation = all.get("delivery_location_display") == null ? "" : all.get("delivery_location").toString();
        controlViewShowState(deliverLocation, mDeliverEditText, null);
        String deliveryLocation = all.get("delivery_location") == null ? "" : all.get("delivery_location").toString();
        mDeliverNavigatorIcon.setTag(R.id.delivery_location, deliveryLocation);
        String detNotes = detail.get("delivery_notes") == null ? "" : detail.get("delivery_notes").toString();
        if (detNotes.length() > 0 && !detNotes.equals("null")) {
            mDeliveryNotes.setVisibility(View.VISIBLE);
            mDeliveryNotes.setText("[ " + detNotes + " ]");
        } else {
            mDeliveryNotes.setVisibility(View.GONE);
        }
        String rName = detail.get("r_name") == null ? "" : detail.get("r_name").toString();
        controlViewShowState(rName, mTaskReName, null);
        String rPhone = detail.get("r_phone") == null ? "" : detail.get("r_phone").toString();
        controlViewShowState(rPhone, mTaskRePhone, null);
//      optional ui
        String collectCash = detail.get("collect_cash") == null ? "" : detail.get("collect_cash").toString();
        Util.debugApp('d', "optional ui collectCash " + collectCash);
        if (!collectCash.equals("null") && collectCash.equals("1")) {
            String collectCashAmount = detail.get("collect_cash_amount") == null ? "" : detail.get("collect_cash_amount").toString();
            Util.debugApp('d', "optional ui  collectCashAmount " + collectCashAmount);
            mTaskTotalFeeSummaryTv.setText("$" + collectCashAmount);
            if (taskStatusId.equals("213") || taskStatusId.equals("223")) {
                mTaskFeeSumSub.setText("Remember collect ");
                mTaskFeeSumAfter.setText(" from customer");
            } else if (taskStatusId.equals("212")) {
                mTaskFeeSumSub.setText("Ask how custom pay ");
                mTaskFeeSumAfter.setText(" when you pickup");
            } else if (taskStatusId.equals("204")) {
                mTaskFeeSumSub.setText("Make sure collect ");
                mTaskFeeSumAfter.setText(" from customer");
            } else if (taskStatusId.equals("201")) {
                mTaskFeeSumSub.setText("You need collect ");
                mTaskFeeSumAfter.setText(" from customer");
            } else if (taskStatusId.equals("202")) {
                mTaskFeeSumSub.setText("Ask how custom pay ");
                mTaskFeeSumAfter.setText(" when you pickup");
            } else if (taskStatusId.equals("203")) {
                mTaskFeeSumSub.setText("You need collect ");
                mTaskFeeSumAfter.setText(" from customer");
            }
        } else {
            Util.debugApp('d', "optional ui dismiss ");
            mTaskLitterSummerLayout.setVisibility(View.GONE);
        }
        if (taskStatusId.equals("212")) {
            mTaskPickUpNumberLayout.setVisibility(View.VISIBLE);
            String pickUpNumber = detail.get("pickup_order_number") == null ? "" : detail.get("pickup_order_number").toString();
            controlViewShowState(pickUpNumber, mPickUpNumber, null);
            String pickUpSecureNumber = detail.get("pickup_secuce_code") == null ? "" : detail.get("pickup_secuce_code").toString();
            if (pickUpSecureNumber.length() > 0 && !pickUpSecureNumber.equals("null")) {
                mPickUpSecureNumber.setText(pickUpSecureNumber);
            } else {
                mPickUpSecureNumber.setVisibility(View.GONE);
                mPickUpSecureNumberSub.setVisibility(View.GONE);
            }
        } else {
            mTaskPickUpNumberLayout.setVisibility(View.GONE);
        }
        Util.debugApp('d', "update UI s_note字段");
        String note = detail.get("s_note") == null ? "" : detail.get("s_note").toString();
        controlViewShowState(note, mTaskDetailNoteEditText, mTaskDetail212Layout);
        String id = detail.get("taskid") == null ? "" : detail.get("taskid").toString();
        controlViewShowState(id, mTask202IdTv, mTask202IdLayout);
        String totalEarnings = "$ " + earning.get("total_earnings") == null ? "" : earning.get("total_earnings").toString();
        String totalEarningsSub = "";
        if (taskStatusId.equals("201")) {
            totalEarningsSub = "Your will earn: $";
        } else if (taskStatusId.equals("202") || taskStatusId.equals("203") || taskStatusId.equals("212") || taskStatusId.equals("213") || taskStatusId.equals("223")) {
            totalEarningsSub = "Total Earnings: $";
        } else if (taskStatusId.equals("204")) {
            totalEarningsSub = "Your Earned: $";
        }
        controlViewShowState(totalEarningsSub + totalEarnings, mTaskFeePriceTv, null);
        String detailTip = all.get("driver_delivery_slip") == null ? "" : all.get("driver_delivery_slip").toString();
        mTask202DetailEditText.setText(detailTip);
        String allowStatus = detail.get("allowed_driver_following_status") == null ? "" : detail.get("allowed_driver_following_status").toString();
        Util.debugApp('d', "update allowStatus" + allowStatus);
        HashMap<String, String> allowStatusMap = Util.parseResponse(allowStatus);
        if (allowStatusMap != null) {
            for (String key : allowStatusMap.keySet()) {
                mSlideToggleView.setText(allowStatusMap.get(key));
                mSlideToggleView.setTag(R.id.task_status_id, key);
                if (key.equals("204")) {
                    mAddPicsLayout.setVisibility(View.VISIBLE);
                    mAddNoteLayout.setVisibility(View.VISIBLE);
                } else {
                    mAddPicsLayout.setVisibility(View.GONE);
                    mAddNoteLayout.setVisibility(View.GONE);
                }
            }
            mSlideToggleView.setTag(R.id.taskid, detail.get("taskid").toString());
            //        dismiss seek bar when allowed_driver_following_status is empty
            if (allowStatus.length() == 0 || allowStatus.equals("null")) {
                mTaskDetailFeeParentLayout.setVisibility(View.GONE);
                selectList.clear();
                adapter.notifyDataSetChanged();
                mAddPicsLayout.setVisibility(View.GONE);
                mAddNoteLayout.setVisibility(View.GONE);
            }
        } else {
            mTaskDetailFeeParentLayout.setVisibility(View.GONE);
            selectList.clear();
            adapter.notifyDataSetChanged();
            mAddPicsLayout.setVisibility(View.GONE);
            mAddNoteLayout.setVisibility(View.GONE);
        }
        if (taskStatusId.length() > 0 && !taskStatusId.equals("null") && taskStatusId.equals("201")) {
            mCountDownView.setVisibility(View.VISIBLE);
            mCountDownView.startCountDown();
        } else {
            mCountDownView.setVisibility(View.GONE);
        }
    }

    private void controlViewShowState(String content, TextView v, View parent) {
        if (content.length() > 0 && !content.equals("null")) {
            v.setVisibility(View.VISIBLE);
            v.setText(content);
        } else {
            v.setVisibility(View.GONE);
            if (parent != null) {
                parent.setVisibility(View.GONE);
            }
        }
    }

    private void sendTaskItemDetail(String id) {
        Util.debugApp('d', "task id " + id);
        if (mLoginToken != null && mUuid != null) {
            CommonOkHttpClient okHttpInstance = CommonOkHttpClient.getInstance(this);
            Map<String, String> headersParams = new HashMap<>();
            headersParams.put("token", mLoginToken);
            this.addLocationParams(headersParams);
            String taskUrl = Constants.ROOT + mUuid + Constants.DETAIL_TASK_ITEM;
            Util.debugApp('d', "task detail info url " + taskUrl);
            Map<String, String> params = new HashMap<>();
            params.put("taskid", id);
            okHttpInstance.doGet(taskUrl, headersParams, params);
        }
    }

    private void addLocationParams(Map<String, String> headersParams) {
        Util.debugApp('d', "add location params " + mUpdateLocation + " " + mLatitude + " " + mLongitude);
        if (mUpdateLocation.equals("true") && !TextUtils.isEmpty(mLatitude) && !TextUtils.isEmpty(mLongitude)) {
            headersParams.put("lat", mLatitude);
            headersParams.put("lng", mLongitude);
        }
    }

    private void updateTask(String taskId, String actionId) {
        Util.debugApp('d', "update task params " + taskId + " " + actionId);
        if (mLoginToken != null && mUuid != null) {
            String updateUrl = Constants.ROOT + mUuid + Constants.UPDATE_TASK;
            Util.debugApp('d', "get update url " + updateUrl);
            CommonOkHttpClient okHttpInstance = CommonOkHttpClient.getInstance(this);
            if (mAddPicsLayout.isShown()) {
                Util.debugApp('d', "update url with pics");
                Map<String, String> headersParams = new HashMap<>();
                headersParams.put("token", mLoginToken);
                this.addLocationParams(headersParams);
                Map<String, String> bodyParams = new HashMap<>();
                bodyParams.put("taskid", taskId);
                bodyParams.put("task_status_id", actionId);
                String noteValue = mEditNote.getText().toString().trim();
                bodyParams.put("note", noteValue);
                Map<String, String> filePathParams = new HashMap<>();
                Util.debugApp('d', "upload pics size " + selectList.size());
                for (int index = 0; index < selectList.size(); index++) {
                    LocalMedia media = selectList.get(index);
                    if (media.isCompressed()) {
                        filePathParams.put("driver_conf_img" + index, media.getCompressPath());
                    } else {
                        filePathParams.put("driver_conf_img" + index, media.getPath());
                    }
                    Util.debugApp('d', "AAB 图片地址 " + selectList.get(index).getPath() + " 压缩地址" + selectList.get(index).getCompressPath());
//                    filePathParams.put("driver_conf_img" + index, selectList.get(index).getPath());
                }
                Util.debugApp('d', "upload pics size " + filePathParams.size());
                okHttpInstance.doPostWithFile(updateUrl, headersParams, bodyParams, filePathParams);
            } else {
                Util.debugApp('d', "update task with no pics");
                Map<String, String> headersParams = new HashMap<>();
                headersParams.put("token", mLoginToken);
                this.addLocationParams(headersParams);
                Map<String, String> params = new HashMap<>();
                params.put("taskid", taskId);
                params.put("task_status_id", actionId);
                okHttpInstance.doPost(updateUrl, headersParams, params);
            }
        }
    }

    private void showProgressDialog(String title) {
        if (mProgressDialog != null) {
            mProgressDialog.setMessage(title);
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.show();
        }
    }

    private void closeProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing() && isValidActivity()) {
            mProgressDialog.dismiss();
        }
    }

    private boolean isValidActivity() {
        if (!isDestroyed() && !isFinishing()) {
            return true;
        }
        return false;
    }

    public boolean isHasGPSModule() {
        if (mLocationManager != null) {
            List<String> mProviders = mLocationManager.getAllProviders();
            if (mProviders != null && mProviders.contains(LocationManager.GPS_PROVIDER)) {
                return true;
            }
        }
        return false;
    }

    private boolean checkGPSIsOpen() {
        if (mLocationManager != null) {
            return mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        }
        return false;
    }

    @Override
    public void success(Response response) {
        Message getTaskSuccessMessage = mHandler.obtainMessage();
        Bundle bundle = new Bundle();
        try {
            String body = response.body().string();
            getTaskSuccessMessage.what = Constants.PROGRESS_RECEIVE_SUCCESS_MESSAGE;
            bundle.putString("taskBody", body);
            getTaskSuccessMessage.setData(bundle);
            Util.debugApp('d', "get json success " + body);
        } catch (IOException e) {
            Util.debugApp('e', "get json success but parse error" + e.toString());
            getTaskSuccessMessage.what = Constants.LOGIN_SUCCESS_FORMAT_ERROR;
        }
        mHandler.sendMessage(getTaskSuccessMessage);
    }

    @Override
    public void fail(IOException exception) {
        exception.printStackTrace();
        Util.debugApp('d', "get json fail " + exception.toString());
        Message getTaskFailMessage = mHandler.obtainMessage();
        getTaskFailMessage.what = Constants.PROGRESS_RECEIVE_FAIL_MESSAGE;
        mHandler.sendMessage(getTaskFailMessage);
    }

    @Override
    public void codeInvalid(Response response) {
        Message unKnowMessage = mHandler.obtainMessage();
        int code = response.code();
        if (code == 401) {
            unKnowMessage.what = Constants.UN_KNOW_RESPONSE_401_CODE;
        } else {
            try {
                String body = response.body().string();
                Util.debugApp('d', "codeInvalid " + body);
                Bundle bundle = new Bundle();
                bundle.putString("codeInvalid", body);
                unKnowMessage.what = Constants.UN_KNOW_RESPONSE_CODE;
                unKnowMessage.setData(bundle);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        mHandler.sendMessage(unKnowMessage);
    }

    @Override
    public void onClick(View v) {
        boolean connect = Util.isNetworkAvailable(this);
        if (!connect) {
            showToast("Please check your network state");
            return;
        }
        int id = v.getId();
        switch (id) {
            case R.id.task_202_id:
                Util.debugApp('d', "task status id 202,task id click");
                if (mTask202DetailEditText.isShown()) {
                    mTask202DetailEditText.setVisibility(View.GONE);
                } else {
                    mTask202DetailEditText.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.task_collect_navigation:
                Object tag = mCollectNavigator.getTag(R.id.pickup_location);
                if (tag != null) {
                    mPickUpLocation = tag.toString();
                    Util.debugApp('d', "task_collect_navigation click " + mPickUpLocation);
                    registerLocationListen();
                    this.showGoogleMapAc(mPickUpLocation);
                }
                break;
            case R.id.task_deliver_navigation:
                Object tagDeliver = mDeliverNavigatorIcon.getTag(R.id.delivery_location);
                if (tagDeliver != null) {
                    mPickUpLocation = tagDeliver.toString();
                    Util.debugApp('d', "task_deliver_navigation click " + mPickUpLocation);
                    registerLocationListen();
                    this.showGoogleMapAc(mPickUpLocation);
                }
                break;
        }
    }

    @Override
    public void onLocationChanged(@NonNull Location location) {
        updateWithNewLocation(location);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(@NonNull String provider) {

    }

    @Override
    public void onProviderDisabled(@NonNull String provider) {

    }

    @Override
    public void onBlockPositionChanged(SlideToggleView view, int left, int total, int slide) {
    }

    @Override
    public void onSlideOpen(SlideToggleView view) {
        boolean connect = Util.isNetworkAvailable(this);
        if (!connect) {
            showToast("Please check your network state");
            return;
        }
        Util.debugApp('d', "onSlideOpen open ");
        if (mCountDownView != null && mCountDownView.isShown()) {
            mCountDownView.stopCountDown();
        }
        String itemTaskId = (String) mSlideToggleView.getTag(R.id.taskid);
        String actionId = (String) mSlideToggleView.getTag(R.id.task_status_id);
        Util.debugApp('d', "Quick Action click taskid " + itemTaskId + " actionId " + actionId);
        showProgressDialog("Please wait...");
        updateTask(itemTaskId, actionId);
    }

    @Override
    public void countDownFinished() {
        Util.debugApp('d', "countDownFinished");
        Intent intent = new Intent();
        intent.setClass(this, FlashDriverPackageListActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("reShowPackage", "true");
        bundle.putString("taskId", mTaskId);
        intent.putExtras(bundle);
        this.startActivity(intent);
        this.finish();
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    private static class FlashDriverTaskDetailHandler extends Handler {

        private final WeakReference<FlashDriverTaskDetailActivity> mActivity;

        private FlashDriverTaskDetailHandler(FlashDriverTaskDetailActivity ac) {
            this.mActivity = new WeakReference<FlashDriverTaskDetailActivity>(ac);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            FlashDriverTaskDetailActivity activity = mActivity.get();
            if (activity != null && !activity.isFinishing()) {
                activity.closeProgressDialog();
                switch (msg.what) {
                    case Constants.GET_TASK_DETAIL:
                        activity.sendTaskItemDetail(activity.mTaskId);
                        break;
                    case Constants.PROGRESS_RECEIVE_SUCCESS_MESSAGE:
                        Util.debugApp('d', "PROGRESS_RECEIVE_SUCCESS_MESSAGE");
                        Bundle bundle = msg.getData();
                        activity.parseDetailContent(bundle);
                        break;
                    case Constants.PROGRESS_RECEIVE_FAIL_MESSAGE:
                        Util.debugApp('d', "PROGRESS_RECEIVE_FAIL_MESSAGE");
                        break;
                    case Constants.LOGIN_SUCCESS_FORMAT_ERROR:
                        Util.debugApp('d', "LOGIN_SUCCESS_FORMAT_ERROR");
                        break;
                    case Constants.UN_KNOW_RESPONSE_401_CODE:
                        activity.showLoginActivity();
                        break;
                    case Constants.UN_KNOW_RESPONSE_CODE:
                        Bundle bundleUnKnowCode = msg.getData();
                        String unKnowBody = bundleUnKnowCode.getString("codeInvalid");
                        String description = Util.getJsonKeyValue("description", unKnowBody);
                        if (description == null) {
                            activity.showToast("Network Error");
                        } else {
                            activity.showToast(description);
                        }
                        break;
                }
            }
        }
    }
}
